//
//  PayNow.m
//  PayNow
//
//  Created by 涂俊 on 2018/1/31.
//  Copyright © 2018年 wyht. All rights reserved.
//

#import "PayNow.h"
#import "OpenSDK_H5ViewController.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_ReqDataGenerator.h"
#import "OpenSDK_StatisticsManager.h"
#import "OpenSDK_PayManager.h"

@interface PayNow () <H5ViewController_Delegate>

@end

@implementation PayNow
{
    NSString *curOrderID;
    //当前的订单信息
    OpenSDK_PayResData *curPayInfo;
}

#pragma mark - OpenSDK_SdkProtrol声明方法
- (void)initInfo {}

#pragma mark - OpenSDK_SdkProtrol声明方法 - 服务器唯一标识
-(NSString *) getServerName {
    return @"PayNow";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 展示的图标
-(NSString *) getDisplayIcon {
    return @"op_pay_paynow.png";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 展示的名字
-(NSString *) getDisplayName {
    return @"微信支付";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 支付平台名
-(NSString *) getPlatform {
    return @"PayNow";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 支付平台版本号
-(NSString *) getPlatformVersion {
    return @"1.0";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 统计的类型名
-(NSString *) getStatisticsType {
    return @"PAYNOW_WECHAT_H5";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 调起第三方平台支付，传入opensdk订单号
-(void) startPay:(OpenSDK_PayResData *) opensdkOrder {
    curPayInfo = opensdkOrder;
    curOrderID = [curPayInfo getOrderID];
    // 服务器返回的调起银联h5支付的地址和参数
    NSDictionary *extra = [opensdkOrder.content objectForKey:@"extra"];
    NSString *postUrl = extra ? [extra objectForKey:@"url"] : nil;
    NSString *postBody = extra ? [extra objectForKey:@"data"] : nil;
    
    if (!postUrl || !postBody) {
        [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_PAY_SUB_FAIL orderId:nil cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType] failInfo:[NSString stringWithFormat:@"现在支付H5支付失败,url=%@,data=%@", postUrl, postBody]];
        // 回调支付失败
        [[OpenSDK_PayManager getInstance] callbackPayFail:@"抱歉，支付失败(支付地址异常)" withOrder:nil];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        OpenSDK_H5ViewController *h5View=[[[OpenSDK_H5ViewController alloc] init] openWithPostUrl:postUrl body:postBody jsMethods:@[@"onCancel", @"onSuccess"]];
        h5View.delegate = self;
        h5View.hasCloseBtn = YES;
        UIViewController *root=[OpenSDK_UIUtil getCurrentVC];
        //弹出透明背景
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
            h5View.modalPresentationStyle=UIModalPresentationOverCurrentContext;
        }else{
            root.modalPresentationStyle=UIModalPresentationCurrentContext;
        }
        [root presentViewController:h5View animated:false completion:^{
        }];
    });
}


- (void) callbackWithName:(NSString *) name args:(id) obj {
    if ([@"onCancel" isEqualToString:name]) {
        // 统计支付取消
        [[OpenSDK_StatisticsManager getInstance] collectPayCancelWithCpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType]];
        // 回调支付取消
        [[OpenSDK_PayManager getInstance] callbackPayCancel];
    } else if ([@"onSuccess" isEqualToString:name]) {
        // 统计渠道支付成功
        [[OpenSDK_StatisticsManager getInstance] collectPaySuccessWithType:OPENSDK_STATS_PAY_SUB_SUCCESS orderId:[curPayInfo getOrderID] cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType]];
        // 支付成功
        NSMutableDictionary *orderDic=[OpenSDK_ReqDataGenerator generateInitDataWithInfo];
        [orderDic setObject:[self getPlatform] forKey:OpenSDK_S_PLATFORM];
        [orderDic setObject:[self getPlatformVersion] forKey:OpenSDK_S_PLATFORM_VERSION];
        NSString *orderStr=[OpenSDK_ReqDataGenerator generateDataByDictionary:orderDic];
        [self checkOrderWithData:orderStr orderID:curOrderID httpDelegate:^(OpenSDK_BaseResData *resData) {
            if([resData isOk]) {
                // 统计checkOrder成功
                [[OpenSDK_StatisticsManager getInstance] collectPaySuccessWithType:OPENSDK_STATS_PAY_SUB_CHECK_SUCCESS orderId:[curPayInfo getOrderID] cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType]];
                // 回调支付成功
                OpenSDK_PayResData *payInfo=[[OpenSDK_PayResData alloc] initWithDictionary:[resData content]];
                OpenSDK_OrderInfo *userOrderInfo=[payInfo toUserOrderInfo];
                [[OpenSDK_PayManager getInstance] callbackPaySuccess:nil withOrder:userOrderInfo];
            } else {
                // 统计checkOrder失败
                [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_PAY_SUB_CHECK_FAIL orderId:nil cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType] failInfo:[resData errorMsg]];
                // 回调支付失败
                [[OpenSDK_PayManager getInstance] callbackPayFail:[resData errorMsg] withOrder:nil];
            }
        }];
    }
}

- (void) close {
    NSMutableDictionary *orderDic=[OpenSDK_ReqDataGenerator generateInitDataWithInfo];
    [orderDic setObject:[self getPlatform] forKey:OpenSDK_S_PLATFORM];
    [orderDic setObject:[self getPlatformVersion] forKey:OpenSDK_S_PLATFORM_VERSION];
    NSString *orderStr=[OpenSDK_ReqDataGenerator generateDataByDictionary:orderDic];
    [self checkOrderWithData:orderStr orderID:curOrderID httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            // 统计checkOrder成功
            [[OpenSDK_StatisticsManager getInstance] collectPaySuccessWithType:OPENSDK_STATS_PAY_SUB_CHECK_SUCCESS orderId:[curPayInfo getOrderID] cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType]];
            // 回调支付成功
            OpenSDK_PayResData *payInfo=[[OpenSDK_PayResData alloc] initWithDictionary:[resData content]];
            OpenSDK_OrderInfo *userOrderInfo=[payInfo toUserOrderInfo];
            [[OpenSDK_PayManager getInstance] callbackPaySuccess:nil withOrder:userOrderInfo];
        } else {
            // 统计checkOrder失败
            [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_PAY_SUB_CHECK_FAIL orderId:nil cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType] failInfo:[resData errorMsg]];
            // 回调支付失败
            [[OpenSDK_PayManager getInstance] callbackPayFail:[resData errorMsg] withOrder:nil];
        }
    }];
}

@end
